import React from 'react';
import { Form, message, Modal, Radio } from 'antd';
import { withRouter, connect } from 'umi';
import AuthComponent from '@/utils/auth/AuthComponent';
import { Icon } from '../components';
import { updateDemandStatus } from '../service';

function DemandChangeStatus({ data = {}, location, onSuccess = () => {}, onClick = () => {}, ...rest }) {
    const { query = {} } = location;
    const [visible, setVisible] = React.useState(false);
    const [value, setValue] = React.useState(data.recruitStatus);
    const [submitting, setSubmitting] = React.useState(false);

    const handleUpdate = async () => {
        setSubmitting(true);
        try {
            const res = await updateDemandStatus({
                recruitStatus: value,
                id: Number(query.id || data.id)
            });
            if (res.code === 10000) {
                message.success('状态变更成功！');
                setVisible(false);
                onSuccess();
            } else {
                message.error('状态变更失败！');
            }
        } catch (error) {
            console.error(error);
        }
        setSubmitting(false);
    };

    const formItemLayout = {
        labelCol: {
            xs: { span: 24 },
            sm: { span: 5 }
        },
        wrapperCol: {
            xs: { span: 24 },
            sm: { span: 16 }
        }
    };

    return (
        <AuthComponent code="office:recruitment:course:requirement:status:edit">
            <Icon
                title="状态变更"
                type="zhuangtaibiangeng"
                onClick={() => {
                    onClick();
                    setVisible(true);
                }}
                {...rest}
            />
            <Modal
                width={600}
                title="状态变更"
                visible={visible}
                okButtonProps={{ disabled: ![4, 5].includes(value) }}
                confirmLoading={submitting}
                onOk={handleUpdate}
                onCancel={() => {
                    setVisible(false);
                }}
            >
                <Form {...formItemLayout} style={{ padding: '24px 0' }}>
                    <Form.Item label="状态变更">
                        <Radio.Group
                            value={value}
                            onChange={e => {
                                setValue(e.target.value);
                            }}
                        >
                            <Radio value={4}>完成招聘</Radio>
                            <Radio value={5}>取消招聘</Radio>
                        </Radio.Group>
                    </Form.Item>
                </Form>
            </Modal>
        </AuthComponent>
    );
}
export default withRouter(connect()(DemandChangeStatus));
